package com.yanq.liancar.activity;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LacquerReservationActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_carType)
    TextView tvCarType;
    @BindView(R.id.ll_car_type)
    RelativeLayout llCarType;
    @BindView(R.id.et_serviceblurb)
    EditText etServiceblurb;
    @BindView(R.id.et_phone_num)
    EditText etPhoneNum;
    @BindView(R.id.et_Contacts)
    EditText etContacts;
    @BindView(R.id.tv_appointment)
    TextView tvAppointment;
    @BindView(R.id.tv_time)
    TextView tv_time;

    private int carType, id, serviceType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lacquer_reservation);
        Utils.setStatusBar(this, true, false);
        ButterKnife.bind(this);
        id = getIntent().getExtras().getInt("id");
        serviceType = getIntent().getExtras().getInt("type");
        if (serviceType == 3) {
            mTvTitle.setText("美容养护预约");
        } else if (serviceType == 4) {
            mTvTitle.setText("保养维修预约");
        } else if (serviceType == 5) {
            mTvTitle.setText("钣金喷漆预约");
        } else {
            mTvTitle.setText("全车打蜡预约");
        }

    }

    @OnClick({R.id.ll_car_type, R.id.tv_appointment, R.id.tv_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_car_type:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                CarTypeDialog();
                break;
            case R.id.tv_appointment:
                InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm2.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                LacquerReservation();
                break;
            case R.id.tv_time:
                InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm1.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                yearPickerView();
                break;
        }
    }

    private void CarTypeDialog() {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.cartype_dialog, null);
        final TextView smallcar = contentView.findViewById(R.id.tv_smallcar);
        final TextView bigcar = contentView.findViewById(R.id.tv_bigcar);
        final TextView suvcar = contentView.findViewById(R.id.tv_SUVcar);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - 80;
        params.bottomMargin = 20;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        //textview_border_blue_write
        smallcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carType = 0;
                smallcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
                smallcar.setTextColor(getResources().getColor(R.color.white));
                bigcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                bigcar.setTextColor(getResources().getColor(R.color.main_color));
                suvcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                suvcar.setTextColor(getResources().getColor(R.color.main_color));
                tvCarType.setText("小型汽车");
                bottomDialog.dismiss();
            }
        });
        bigcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carType = 1;
                smallcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                smallcar.setTextColor(getResources().getColor(R.color.main_color));
                bigcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
                bigcar.setTextColor(getResources().getColor(R.color.white));
                suvcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                suvcar.setTextColor(getResources().getColor(R.color.main_color));
                tvCarType.setText("大型汽车");
                bottomDialog.dismiss();
            }
        });
        suvcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                carType = 2;
                smallcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                smallcar.setTextColor(getResources().getColor(R.color.main_color));
                bigcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
                bigcar.setTextColor(getResources().getColor(R.color.main_color));
                suvcar.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
                suvcar.setTextColor(getResources().getColor(R.color.white));
                tvCarType.setText("SUV汽车");
                bottomDialog.dismiss();
            }
        });

    }

    //预约
    private void LacquerReservation() {
        if (isNull()) {
            OkGo.<String>post(Config.s + "llc/destineCarService")
                    .tag(this)
                    .params("token", UserBean.getcToken(this))
                    .params("carType", carType)
                    .params("carNum", etServiceblurb.getText().toString().trim())
                    .params("tel", etPhoneNum.getText().toString().trim())
                    .params("gainName", etContacts.getText().toString().trim())
                    .params("type", serviceType)
                    .params("carType", carType)
                    .params("sid", id)
                    .params("destineDate", tv_time.getText().toString().trim())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                            if (baseBean.isIsSuccess()) {
                                RxToast.success(baseBean.getOutputMessage());
                                finish();
                            } else {
                                RxToast.error(baseBean.getOutputMessage());
                            }
                        }
                    });
        }
    }

    private boolean isNull() {
        if (TextUtils.isEmpty(etServiceblurb.getText().toString().trim())) {
            RxToast.info("请填写车牌号码");
            return false;
        }
        if (TextUtils.isEmpty(etPhoneNum.getText().toString().trim())) {
            RxToast.info("请填写手机号码");
            return false;
        }
        if (TextUtils.isEmpty(etContacts.getText().toString().trim())) {
            RxToast.info("请填写联系人");
            return false;
        }
        LogUtils.e("isValidDate", isValidDate(tv_time.getText().toString().trim()) + "");
        if (!isValidDate(tv_time.getText().toString().trim())) {
            RxToast.info("请选择预约时间");
            return false;
        }
        return true;
    }

    private void yearPickerView() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(1990, 0, 1);
        endDate.set(2050, 11, 31);


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {

                String Startdate = getTime(date);
                LogUtils.e("Startdate", Startdate);
                LogUtils.e("Startdate", date.toString());
                tv_time.setText(Startdate);
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                .setTitleBgColor(0xFFd6d6d6)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .setBgColor(0xFFffffff)
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    /**
     * @param datdString Thu May 18 2017 00:00:00 GMT+0800 (中国标准时间)
     * @return 年月日;
     */
    public static String parseTime(String datdString) {
        datdString = datdString.replace("GMT", "").replaceAll("\\(.*\\)", "");
        //将字符串转化为date类型，格式2016-10-12
        SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
        Date dateTrans = null;
        try {
            dateTrans = format.parse(datdString);
            return new SimpleDateFormat("yyyy-MM-dd hh:mm").format(dateTrans).replace("-", "/");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return datdString;

    }

    /**
     * @param str 判断字符串是否是标准时间格式
     */
    public static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

}
